import axios, { AxiosError } from 'axios'
import { userUserStore } from '@/stores'
import { showFailToast } from 'vant'
import router from '@/router'
import type { Method } from 'axios'
export const baseURL = 'https://consult-api.itheima.net/'
const instance = axios.create({
  // TODO 1. 基础地址，超时时间
  baseURL,
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    //从pinia获取token
    const user = userUserStore()
    // TODO 2. 携带token
    if (user.user?.token && config.headers) {
      config.headers.Authorization = `Bearer ${user.user?.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    // TODO 3. 处理业务失败
    if (res.data.code !== 10000) {
      showFailToast(res.data.message)
      return Promise.reject(res.data.message || '业务失败')
    }
    // TODO 4. 摘取核心响应数据
    return res.data
  },
  (err: AxiosError) => {
    if (err.response?.status === 401) {
      //删除用户信息
      const userStore = userUserStore()
      userStore.delUser()
      //带参跳转首页
      router.push({
        path: `/login`,
        query: {
          returnUrl: router.currentRoute.value.fullPath
        }
      })
    }
    // TODO 5. 处理401错误
    return Promise.reject(err)
  }
)

//定义响应数据类型
type Data<T> = {
  code: number
  message: string
  data: T
}
// 4. 请求工具函数
export const request = <T>(
  url: string,
  method: Method = 'get',
  submitData?: object
) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}
export default instance
